package com.betterwood.dragon.worms;

import java.util.ArrayList;
import java.util.List;

import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.Site;
import com.betterwood.dragon.entity.dto.SearchDTO;
import com.betterwood.dragon.utils.TimeUtil;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ZK {
    // ZK可以正常登陆，但是搜索没有结果
    public static String login(Site site) {
        log.info("#########################################");
        log.info("############START LOGIN TO ZK############");
        String contextState = "EMPTY";

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            BrowserContext context = browser.newContext();

            // Open new page
            Page page = context.newPage();

            // Go to http://www.fuji-pharm.cn/
            // page.navigate(site.getSiteUrl());
            page.navigate("http://www.360yyk.com/");
            page.click("text=请登录");

            page.click("[placeholder=\"请输入账号\"]");
            page.fill("[placeholder=\"请输入账号\"]", "13924205657");
            // Press Enter

            page.click("[placeholder=\"请输入密码\"]");
            // Fill input[name="password"]
            page.fill("[placeholder=\"请输入密码\"]", "13924205657");

            // Press Enter
            // page.waitForNavigation(new
            // Page.WaitForNavigationOptions().setUrl("http://bh.ry600.com/_shop/index.shtml"),
            // () ->
            page.waitForNavigation(() -> {
                page.click("text=立即登录");
            });
            // ---------------------

            contextState = context.storageState();
            // log.info(contextState);
            log.info("############END OF LOGIN TO ZK#############");

        } catch (RuntimeException e) {
            e.printStackTrace();

        }
        return contextState;
    }

    public static List<Result> fetchProduct(Site site, SearchDTO search) {
        log.info("#######################################");
        log.info("############START FETCH FROM ZK########");

        // List<Result> res = getList(site, search);
        List<Result> initList = new ArrayList<>();
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));

            String storageState = site.getLoginInfo();

            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageState(storageState));

            // Open new page
            Page page = context.newPage();

            // Go to http://www.fuji-pharm.cn/
            page.navigate(site.getSiteUrl());
            log.info("**********");
            log.info(search.getKeywordStr());
            log.info("**********");

            // page.pause();

            // page.click("text=热门搜索抢购阿莫西林搜 索搜本店 >> input[name=\"search_text\"]");
            // page.fill("text=热门搜索抢购阿莫西林搜 索搜本店 >> input[name=\"search_text\"]",
            // search.getKeywordStr());

            page.click("[placeholder=\"请输入商品名称\"]");
            // Fill [placeholder="口罩"]
            page.fill("[placeholder=\"请输入商品名称\"]", search.getKeywordStr()); // Click text=搜索

            page.waitForNavigation(() -> {

                page.click("text=搜索");

            });

            // String wait = page.textContent(".spxsjSpanCss");
            log.info("HERE IS THE WAIT PART");
            page.waitForTimeout(3500);
            String content = page.innerHTML(".product-list");

            if (!page.isVisible(".mypage")) {
                log.info("**************NO NEW PRODUCTS!!!******************");

                log.info(Integer.toString(initList.size()));
                log.info("**************NO NEW PRODUCTS!!!******************");
                return initList;
            }

            String pager = page.innerHTML(".mypage");

            // log.info(pager);
            Document pagerDoc = Jsoup.parseBodyFragment(pager);

            Integer size = pagerDoc.getElementsByTag("li").size();

            Element next = pagerDoc.getElementsByTag("li").get(size - 2);

            boolean hasNext = !next.classNames().contains("disable");

            initList = getList(content, search, site);
            List<Result> otherList = new ArrayList<>();

            while (hasNext) {
                page.click("text=下一页");
                page.waitForTimeout(2500);
                content = page.innerHTML(".product-list");

                pager = page.innerHTML(".mypage");
                pagerDoc = Jsoup.parseBodyFragment(pager);
                next = pagerDoc.getElementsByTag("li").get(size - 2);
                hasNext = !next.classNames().contains("disable");
                otherList = getList(content, search, site);
                initList.addAll(otherList);

            }
            // log.info(content);

        } catch (RuntimeException e) {
            e.printStackTrace();
            log.info("WORMA FAILED");
        }

        log.info("END OF fetch product");
        log.info("**************FOUND NEW PRODUCTS!!!******************");

        log.info(Integer.toString(initList.size()));
        log.info("**************FOUND NEW PRODUCTS!!!******************");
        return initList;
    }

    public static List<Result> getList(String content, SearchDTO search, Site site) {

        List<Result> list = new ArrayList<>();

        Document doc = Jsoup.parseBodyFragment(content);
        Element body = doc.body();

        Elements lis = body.getElementsByClass("item");

        if (lis.size() == 0) {
            log.info("ZK HAVE NO RESULTS");
            return list;
        }

        for (Element li : lis) {

            Element nameElement = li.getElementsByClass("pro_detail").first();
            Element aElement = nameElement.getElementsByTag("p").first();
            String pName = aElement.text();

            Element proElement = li.getElementsByClass("pro-val").first();
            Element makerElement = li.getElementsByClass("pro-val").get(1);
            String prop = proElement.text();
            String maker = makerElement.text();

            Element priceEle = li.getElementsByClass("is_price").first();
            // Element emElement = priceEle.getElementsByTag("em").get(1);
            String price = priceEle.text();
            String priceClean = StrUtil.split(price, " ")[1];

            Double priceDouble = NumberUtil.isNumber(priceClean) ? Double.parseDouble(priceClean) : 0;

            // // Elements els = li.getElementsByClass("p-caption");
            // // Element item = els.first().getElementsByTag("a").first();
            // // String pName = item.text();
            // // String orderUrl = item.attributes().get("href");
            // log.info("商品名是:" + pName);
            // log.info("商品规格是:" + prop);
            // log.info("制造商是:" + maker);
            // log.info("价格是:" + priceClean);
            // log.info("数字价格是:" + priceDouble.toString());

            String productName = StrUtil.concat(true, pName, prop, maker);

            Element urlTag = li.getElementsByClass("pro-img").first();
            String orderUrl = urlTag.attributes().get("href");
            String url = StrUtil.concat(true, site.getSiteUrl(), orderUrl);

            // // // String sourcePrice =
            // // // li.getElementsByClass("carousel__item--price").first().text();
            // // String sourcePriceClean = sourcePrice;
            // // log.info("价格是:" + sourcePriceClean);
            // // // String amountLeft = li.getElementsByClass("flex_hei").first().text();

            // // Double priceDouble = NumberUtil.isNumber(sourcePriceClean) ?
            // // Double.parseDouble(sourcePriceClean) : 0;
            // // log.info("数字价格是:" + priceDouble.toString());

            // // log.info("商品购买URL是:" + orderUrl);

            // // // String partnerCode = site.getSiteNo() + sourceCodeClean;

            Result re = new Result();
            re.setKeywordStr(search.getKeywordStr());
            re.setProductName(productName);
            re.setOrderUrl(url);
            re.setProp(prop);
            re.setMaker(maker);
            re.setScanTime(TimeUtil.currentTime());
            re.setSearchId(search.getId());
            re.setSiteName("正康");
            // // // // // re.setSiteId("");
            re.setSiteNo("ZK");
            re.setScanPrice(priceClean);

            re.setPrice(priceDouble);
            re.setStatus(0);

            // // // // // resultDao.save(re);
            list.add(re);

        }

        // // return "SUCCESS";
        // log.info("WORMC SUCCESS");

        return list;
    }
}
